from typing import Dict, Any
from .catalog import get_product
from ..core.state import ORDERS, push_message, now_iso


def handle_user_select_product(product_id: str) -> Dict[str, Any]:
	product = get_product(product_id)
	if not product:
		return push_message("user", "text", "未找到该商品，请重试。")
	from uuid import uuid4
	order_id = uuid4().hex
	ORDERS[order_id] = {
		"orderId": order_id,
		"product": product,
		"status": "PENDING_SALES",
		"createdAt": now_iso(),
	}
	push_message(
		"sales",
		"form",
		f"新订单待确认：{product['name']} (￥{product['price']})",
		{"formType": "salesConfirm", "orderId": order_id, "submitAction": "sales_confirm_to_supplier"}
	)
	return push_message("user", "text", f"已为你创建订单，编号{order_id[:8]}，等待销售确认。")


def handle_sales_confirm_to_supplier() -> Dict[str, Any]:
	pending = [o for o in ORDERS.values() if o["status"] == "PENDING_SALES"]
	if not pending:
		return push_message("sales", "text", "暂无待确认订单。")
	order = sorted(pending, key=lambda x: x["createdAt"], reverse=True)[0]
	order["status"] = "WAIT_SUPPLIER_SHIP"
	product = order["product"]
	push_message(
		"supplier",
		"form",
		f"请发货：{product['name']}，订单号{order['orderId'][:8]}",
		{"formType": "supplierShip", "orderId": order["orderId"], "submitAction": "supplier_submit_shipment"}
	)
	return push_message("sales", "text", f"已通知供应商发货（订单{order['orderId'][:8]}）。")


def handle_supplier_ship(tracking_no: str, company: str) -> Dict[str, Any]:
	waiting = [o for o in ORDERS.values() if o["status"] == "WAIT_SUPPLIER_SHIP"]
	if not waiting:
		return push_message("supplier", "text", "暂无需要发货的订单。")
	order = sorted(waiting, key=lambda x: x["createdAt"], reverse=True)[0]
	order["status"] = "SHIPPED"
	order["shipment"] = {"company": company, "trackingNo": tracking_no, "shippedAt": now_iso()}
	push_message("sales", "text", f"供应商已发货：{company} {tracking_no}（订单{order['orderId'][:8]}）。")
	return push_message("supplier", "text", "发货信息已记录，感谢！")


